package weixin.popular.api;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;

import net.sf.json.JSONObject;
import weixin.popular.bean.Token;

public class TokenAPI extends BaseAPI{
	
	private static String token ="";
	//过期时间/s
	private static long expireTime = 7000;
	//获取token的时间
	private static Date getTokenTime = null;
	
	private static String apiKey = "wx75d128fff81e2225";
	private static String apiSecret = "e79bb2ecf7eefb5901c0c9188126cc5f";

	/**
	 * 获取access_token
	 * @param appid
	 * @param secret
	 * @return
	 */
	public static Token token(String appid,String secret){
		String url = BASE_URI + "/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
		JSONObject jsonObject = httpRequest(url, "GET", null);
		Token token = new Token();
		try{  
			token.setAccess_token(jsonObject.getString("access_token"));
			token.setExpires_in(jsonObject.getInt("expires_in"));
			getTokenTime = new Date();
		}catch(Exception e){ 
		}
		
		try{ 
			token.setErrcode(jsonObject.getString("errcode"));
			token.setErrmsg(jsonObject.getString("errmsg"));
			 
		}catch(Exception e){ 
		}
		
		return token;
	}
	
	public String getToken(){
		if(StringUtils.isNotBlank(token) || (getTokenTime != null && (getTokenTime.getTime() - new Date().getTime()) > expireTime ) ){
			return token;
		}
		Token tokenObj = this.token(apiKey,apiSecret);
		return tokenObj.getAccess_token();
	}
	
	


	@Test
	public void testAPI(){
		Token tokenObj = this.token("wx75d128fff81e2225","e79bb2ecf7eefb5901c0c9188126cc5f");
		System.err.println(tokenObj.toString());
	}

}
